#pragma once
#include "sock.hpp"
class SelectClient
{
public:
    SelectClient(const std::string &serverip, uint16_t serverport)
        : _serverip(serverip), _serverport(serverport)
    {
    }
    void init()
    {
        _sock.Socket();
        int cnt = 5;
        while (_sock.Connect(_serverip, _serverport) != 0)
        {
            std::cout << "正在尝试重连，剩余次数：" << cnt-- << std::endl;
            if (cnt <= 0)
            {
                break;
            }
        }
        if (cnt <= 0)
        {
            std::cerr << "连接失败..." << std::endl;
            exit(CONNECT_ERR);
        }
        // 连接成功了
        std::cout << "conneect success" << std::endl;
    }
    void start()
    {
        char buffer[1024];
        while (true)
        {
            std::string message;
            std::cout << "请输入发送给服务端的信息: ";
            getline(std::cin, message);
            //std::cout<<message;
            ssize_t strSize = send(_sock.GetFd(), message.c_str(), message.size()+1, 0);
            if (strSize <= 0)
            {
                std::cerr << "send fail " << strerror(errno) << std::endl;
            }
            // 接受服务端传来的消息
            ssize_t n = recv(_sock.GetFd(), buffer, sizeof(buffer) - 1, 0);
            if (n > 0)
            {
                buffer[n] = '\0';
                std::cout << "server message :" << buffer << std::endl;
            }
            else if (n == 0)
            {
                std::cerr << "server quit" << std::endl;
                break;
            }
            else
            {
                std::cerr << "recv error: " << strerror(errno) << std::endl;
                break;
            }
        }
    }

private:
    xjc::Sock _sock;
    std::string _serverip;
    uint16_t _serverport;
};